package com.cykj.webSocket;

import com.cykj.chat.service.impl.ChatServiceImpl;
import com.cykj.common.entity.ChatRecordDO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @BelongsProject: smart_recruit_backend
 * @BelongsPackage: com.cykj.webSocket
 * @Author: 蔡张君逸
 * @CreateTime: 2025-08-27 11:20
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class AddWebSocketHandler extends TextWebSocketHandler {
    public static final ConcurrentMap<String,WebSocketSession>userSessionMap=new ConcurrentHashMap<>();
    public static final ConcurrentMap<String,WebSocketSession>hrSessionMap=new ConcurrentHashMap<>();
    public static final ConcurrentMap<String,WebSocketSession>adminSessionMap=new ConcurrentHashMap<>();
    @Autowired
    private ChatServiceImpl chatService;
    @Autowired
    ObjectMapper objectMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        URI uri = session.getUri();
        MultiValueMap<String, String> queryParams = UriComponentsBuilder.fromUri(uri).build().getQueryParams();
        String role = queryParams.getFirst("role");
        String id = queryParams.getFirst("id");
        switch (role) {
            case "user" -> userSessionMap.put(id, session);
            case "hr" -> hrSessionMap.put(id, session);
            case "admin" -> adminSessionMap.put(id, session);
        }
        super.afterConnectionEstablished(session);
    }
//监听前端调用发送消息事件(可选)
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        ChatRecordDO chatRecordDO = objectMapper.readValue(payload, ChatRecordDO.class);
        chatService.writeRecord(chatRecordDO);
        super.handleTextMessage(session, message);
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        URI uri = session.getUri();
        MultiValueMap<String, String> queryParams = UriComponentsBuilder.fromUri(uri).build().getQueryParams();
        String role = queryParams.getFirst("role");
        String id = queryParams.getFirst("id");
        switch (role) {
            case "user" -> userSessionMap.remove(id);
            case "hr" -> hrSessionMap.remove(id);
            case "admin" -> adminSessionMap.remove(id);
        }
        super.afterConnectionClosed(session, status);
    }
//    发送消息触发对前端提醒
    public static void sendMessage(String role,Integer id) {
        try {
            switch(role){
                case "user" -> {
                    WebSocketSession webSocketSession = userSessionMap.get(String.valueOf(id));
                    if(webSocketSession!=null){
                        webSocketSession.sendMessage(new TextMessage("发送完成"));
                    }
                }
                case "hr" -> {
                    WebSocketSession webSocketSession = hrSessionMap.get(String.valueOf(id));
                    if(webSocketSession!=null){
                        webSocketSession.sendMessage(new TextMessage("发送完成"));
                    }
                }
                case "admin" -> {
                    WebSocketSession webSocketSession = adminSessionMap.get(String.valueOf(id));
                    if(webSocketSession!=null){
                        webSocketSession.sendMessage(new TextMessage("发送完成"));
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    返回一个随机的在线客服id
    public static String getOnlineAdmin(){
        Set<String> keySet = adminSessionMap.keySet();
        List<String> keys = new ArrayList<>(keySet);
        Random random = new Random();
        if (!keys.isEmpty()){
            int i = random.nextInt(0, keys.size());
            return keys.get(i);
        }else {
//            无在线客服
            System.err.println("1111");
            return "2";
        }


    }
}